/**	
 * Author : Mht
 * Desc : For 2016 RDM 
 */
package service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import lombok.extern.log4j.Log4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @author Mht
 * @date May 10, 2016
 */
@Log4j
@Service
public class RedisService {

	private static String ADDR = "127.0.0.1";

	private static int PORT = 6379;

	private static String AUTH = "admin";

	private static int MAX_ACTIVE = 1024;

	private static int MAX_IDLE = 200;

	private static int MAX_WAIT = 10000;

	private static int TIMEOUT = 10000;

	private static boolean TEST_ON_BORROW = true;

	@Autowired
	@Qualifier("jedisPoolConfig")
	private JedisPoolConfig config;

	private JedisPool jedisPool;

	/**
	 * ��ʼ��Redis���ӳ�
	 */
	// static {
	// try {
	// JedisPoolConfig config = new JedisPoolConfig();
	// config.setMaxTotal(MAX_ACTIVE);
	// config.setMaxIdle(MAX_IDLE);
	// config.setTestOnBorrow(TEST_ON_BORROW);
	// jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT);
	// log.info("Redis Server connected at port : " + PORT);
	// } catch (Exception e) {p
	// e.printStackTrace();
	// }
	// }

	/**
	 * ��ȡJedisʵ��
	 * 
	 * @return
	 */
	public synchronized Jedis getJedis() {
		try {
			jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT);
			if (jedisPool != null) {
				Jedis resource = jedisPool.getResource();
				return resource;
			} else {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * �ͷ�jedis��Դ
	 * 
	 * @param jedis
	 */
	public void returnResource(final Jedis jedis) {
		if (jedis != null) {
			jedis.close();
		}
	}

}
